package com.shamine.kuaiqiao.blink.gallery.create

import android.app.Activity
import android.app.Dialog
import android.content.Intent
import android.graphics.BitmapFactory
import android.net.Uri
import android.os.Bundle
import android.view.View
import android.widget.ImageView
import cn.bmob.v3.BmobUser
import cn.bmob.v3.datatype.BmobFile
import cn.bmob.v3.exception.BmobException
import cn.bmob.v3.listener.SaveListener
import cn.bmob.v3.listener.UploadFileListener
import com.shamine.kuaiqiao.blink.data.Gallery
import com.theartofdev.edmodo.cropper.CropImage
import com.theartofdev.edmodo.cropper.CropImageView
import dmax.dialog.SpotsDialog
import kotlinx.android.synthetic.main.activity_add_gallery.*
import com.shamine.kuaiqiao.blink.R
import com.shamine.kuaiqiao.blink.basic.BaseActivity
import com.shamine.kuaiqiao.blink.data.Passer
import com.shamine.kuaiqiao.blink.events.EventAddGallery
import com.shamine.kuaiqiao.blink.events.EventSignOut
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import java.io.File

class AddGallery : BaseActivity() ,View.OnClickListener{
    private lateinit var dialog: Dialog
    private lateinit var mCropImageUri: Uri

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_add_gallery)
        EventBus.getDefault().register(this)
        setSupportActionBar(toolbar_add)

        dialog = SpotsDialog(this,R.style.DialogWait)
    }

    override fun onClick(p0: View?) {
        when(p0?.id){
            R.id.cover -> CropImage.startPickImageActivity(this)
            R.id.create -> check()
        }
    }

    /**
     * 标记是否设置封面
     */
    private var coverSet: Boolean = false

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode != Activity.RESULT_OK) return else {
            when(requestCode){
                /**
                 *选择照片来源结果
                 */
                CropImage.PICK_IMAGE_CHOOSER_REQUEST_CODE -> {
                    CropImage.activity(CropImage.getPickImageResultUri(this, data))
                            .setInitialCropWindowPaddingRatio(0.0f)//最大化裁剪窗口
                            .setAspectRatio(9,16)
                            .setCropShape(CropImageView.CropShape.RECTANGLE)
                            .setMinCropResultSize(900,1600)
                            .setMaxCropResultSize(1800,3200)
                            .start(this)
                }
                //裁剪的结果
                CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE -> {
                    val result = CropImage.getActivityResult(data)
                    mCropImageUri = result.uri
                    if (resultCode == RESULT_OK) {
                        //resultUri.path: /data/user/0/com.shamine.kuaiqiao.blink/cache/cropped1370004873.jpg
                        cover.scaleType = ImageView.ScaleType.CENTER_CROP
                        cover.setImageBitmap(BitmapFactory.decodeFile(result.uri.path))
                        coverSet = true
                    } else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
                        val error = result.error
                        toast(this,error.message.toString())
                    }
                }
            }
        }
    }

    /**
     * 检查信息完整性并创建
     */
    private fun check() {
        val content = galleryTitle.text.toString()
        if (content.isEmpty()){
            toast(this,getString(R.string.toast_title_unset))
            return
        }
        if (!coverSet) {
            toast(this,getString(R.string.toast_set_cover))
            return
        }
        dialog.show()
        createTypeOne()
    }

    /**
     * 记录成长
     */
    private fun createTypeOne() {
        val file = BmobFile(File(mCropImageUri.path))
        file.upload(object : UploadFileListener(){
            override fun done(p0: BmobException?) {
                //图片上传完成 保存相册
                if (p0 == null) {
                    val gallery = Gallery(
                            BmobUser.getCurrentUser<Passer>(Passer::class.java),
                            galleryTitle.text.toString(),
                            0,
                            file,
                            false)

                    gallery.save(object: SaveListener<String>(){
                        override fun done(oid: String?, p1: BmobException?) {
                            dialog.dismiss()
                            if (p1==null){
                                //相册创建成功,通知主页刷新
                                EventBus.getDefault().post(EventAddGallery())
                                finish()
                            }else toast(this@AddGallery,p1.message.toString())
                        }
                    })
                } else {
                    dialog.dismiss()
                    toast(this@AddGallery,getString(R.string.toast_create_gallery_failed)+p0.message.toString())
                }
            }
        })
    }

    @Subscribe
    override fun onSignOut(event: EventSignOut) {
        EventBus.getDefault().unregister(this)
        finish()
    }

    override fun onDestroy() {
        EventBus.getDefault().unregister(this)
        super.onDestroy()
    }
}
